<?php
/**
 * 防页面Refresh插件的实现
 *
 * @category   Framework
 * @package    Plugin
 */

/**
*需要注意的几个默认规则：
*    1. 本插件类的文件名必须是action
*    2. 插件类的名称必须是{插件名_actions}
*/
class Plugin_Refresh implements Zero_Plugin_Interface
{
    //解析函数的参数是pluginManager的引用
    function __construct()
    {
        //注册这个插件
        //第一个参数是钩子的名称
        //第二个参数是pluginManager的引用
        //第三个是插件所执行的方法
        Zero_Plugin_Manager::getInstance()->register('init', $this, 'say_hello');
        Zero_Plugin_Manager::getInstance()->register('init', $this, 'desc');
    }
    
    function say_hello($data)
    {
        echo 'Hello World';
    }

   function desc($argv=null)
   {
        if (isset($_SERVER['REMOTE_ADDR'])) 
        {
            @session_start();

            $cur_time = $_SERVER['REQUEST_TIME'];
            $refresh_delay = 3; // 刷新间隔限制
            $refresh_limit = 3; // 刷新次数限制

            $lock_time = 20;    // 屏蔽时间
            $write_log = true; // 是否写日志
            $message = '<div class="tips special b">为了大家能更好的访问, 请不要频繁刷新页面！请您在 ' . $lock_time . ' 秒后重新访问！</div>';

            $last_refresh = explode(',', @$_SESSION['last_refresh']);
            $count_refresh = @$_SESSION['count_refresh'];
            
            if ($cur_time - $last_refresh[0] > $lock_time)    
            {
                $count_refresh = 0;
            }
            
            if ($count_refresh >= $refresh_limit)    
            {
                
                if ($write_log && $count_refresh == $refresh_limit) 
                {
                    $path = ROOT_PATH . '/data/logs/refresh_limit.log';
                    
                    if ($fp = @fopen($path, 'a')) 
                    {
                        $data = date("Y/m/d H:i:s") . "    - Page:    " . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . "    - From:    " . $_SERVER['REMOTE_ADDR'] . "\n";
                        $op = @fwrite($fp, $data);
                        fclose($fp);
                    }
                }

                $_SESSION['count_refresh'] = $count_refresh + 1;

                echo ($message);
                exit;
                die();
            }
            elseif ($cur_time - $last_refresh[0] <= $refresh_delay    && $_SERVER['REQUEST_URI'] == $last_refresh[1]) 
            {
                $count_refresh++;
            }
            else
            {
                $count_refresh = 0;
            }

            $_SESSION['count_refresh'] = $count_refresh;
            $_SESSION['last_refresh'] = $cur_time . ',' . $_SERVER['REQUEST_URI'];
        }
   }
}
?>